package com.tgy.algorithm.base;

class Node {
    int num;
    Node next;
    public Node(int num, Node next) {
        this.num = num;
        this.next = next;
    }

    @Override
    public String toString() {
        return "num: " + num;
    }
}

public class _链表反转 {

    public static Node generalNode(int[] nums) {

        if (nums == null || nums.length == 0) {
            return null;
        }

        Node head = null;
        Node cur = null;
       for (int i = 0; i < nums.length; i++) {
           Node next = new Node(nums[i], null);
           if(i == 0) {
               head = next;
               cur = head;
           }else {
               cur.next = next;
               cur = next;
           }
       }

        return head;
    }

    public static void printNode(Node head) {
        Node cur = head;

        while (cur != null) {
            System.out.print(cur.num + " ");
            cur = cur.next;
        }
        System.out.println();
    }

    public static Node reverse(Node head) {
        if (head == null || head.next == null) {
            return head;
        }

        // Node -> Node -> Node
        Node prev = null;
        Node cur = head;
        // 存储下一个节点
        Node next = null;
        while (cur != null) {
            next = cur.next;
            cur.next = prev;
            prev = cur;
            cur = next;
        }

        return prev;
    }

    public static void main(String[] args) {
        Node node = generalNode(new int[] { 1, 2, 3, 4, 5, 6, 7, 8, 9 });
        printNode(node);
        Node reverseNode = reverse(node);
        printNode(reverseNode);
    }
}
